import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { authApi } from "@/apis/auth";
import type { SigninRequest, SignupRequest, SignupResponse } from "@/types/auth";

/**
 * 认证状态管理
 */
export const useAuthStore = defineStore(
  "auth",
  () => {
    // 状态
    const token = ref<string>("");
    const userInfo = ref<SignupResponse | null>(null);
    const isLoading = ref(false);

    // 计算属性
    const isAuthenticated = computed(() => !!token.value);
    const username = computed(() => userInfo.value?.username || "");

    /**
     * 用户登录
     * @param loginData 登录数据
     */
    const signin = async (loginData: SigninRequest) => {
      isLoading.value = true;
      try {
        const response = await authApi.signin(loginData);

        // 保存token
        token.value = response.data.access_token;

        return { success: true, message: "登录成功" };
      } catch (error: any) {
        console.error("登录失败:", error);
        return {
          success: false,
          message: error.message || "登录失败，请稍后重试",
        };
      } finally {
        isLoading.value = false;
      }
    };

    /**
     * 用户注册
     * @param registerData 注册数据
     */
    const signup = async (registerData: SignupRequest) => {
      isLoading.value = true;
      try {
        const response = await authApi.signup(registerData);

        // 保存用户信息
        userInfo.value = response.data;

        return { success: true, message: "注册成功", data: response };
      } catch (error: any) {
        console.error("注册失败:", error);
        return {
          success: false,
          message: error.message || "注册失败，请稍后重试",
        };
      } finally {
        isLoading.value = false;
      }
    };

    /**
     * 用户登出
     */
    const signout = async () => {
      try {
        // 调用后端登出接口，从 Redis 中删除 token
        await authApi.signout();
      } catch (error) {
        console.error("登出失败:", error);
        // 即使后端登出失败，也清除本地 token
      } finally {
        // 清除本地认证信息
        token.value = "";
        userInfo.value = null;
      }
    };

    /**
     * 清除认证状态
     */
    const clearAuth = async () => {
      await signout();
    };

    return {
      // 状态
      token,
      userInfo,
      isLoading,

      // 计算属性
      isAuthenticated,
      username,

      // 方法
      signin,
      signup,
      signout,
      clearAuth,
    };
  },
  {
    persist: {
      key: "auth-store",
      storage: localStorage,
      pick: ["token", "userInfo"],
    },
  },
);
